package org.xiaojl.xcloud.tools.gateway.filter.pre;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.xiaojl.xcloud.tools.gateway.RpcResult;
import org.xiaojl.xcloud.tools.gateway.kit.FilterKit;
import org.xiaojl.xcloud.tools.gateway.kit.JsonKit;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**  
 * <p>Title: TokenFilter</p>  
 *
 * <p>Description: Token认证过滤器<br>
 * 通过配置：zuul.TokenFilter.pre.disable=false 来禁用该过滤器
 * </p>  
 *
 * @author jilong.xiao  
 * @date 2018年4月19日  
 */
@Component
public class TokenFilter extends ZuulFilter {
	private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);
	@Override
	public boolean shouldFilter() {
		// 是否执行该过滤器，此处为true，说明需要过滤  
		return FilterKit.isFilterFlag(RequestContext.getCurrentContext());
	}

	@Override
	public Object run() {
		RequestContext context = RequestContext.getCurrentContext();
		HttpServletRequest request = context.getRequest();
		if(log.isDebugEnabled()){
			log.debug(String.format("%s TokenFilter request to %s", request.getMethod(), request.getRequestURL().toString()));  
		}
		
		String token = request.getParameter("token");
		if(token==null || "".equals(token)){
			RpcResult result = RpcResult.fail("非法请求", "Token信息为空", null);
			
			context.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
			context.setResponseStatusCode(401);// 返回错误码  
			FilterKit.setRespBody(context,  JsonKit.toJson(result));
			FilterKit.setFilterFlag(context,false);
            return null;  
		}
		
		//判断token是否有效
		//System.out.println(String.format("获取到的Token信息： %s", token)); 
		if(!checkToken(token)){
			RpcResult result = RpcResult.fail("非法请求", "无效Token(token过期了或者token错误)", null);
			
			FilterKit.setFilterFlag(context,false);
			context.setSendZuulResponse(false);// 过滤该请求，不对其进行路由
			context.setResponseStatusCode(401);// 返回错误码  
			FilterKit.setRespBody(context,  JsonKit.toJson(result));
            return null; 
		}
		
		//设置用户信息到请求参数中
		if("1234".equals(token)){
			//进入灰度发布服务的用户
			request.setAttribute("grayReleaseUser", "1");
		}
		
		context.setSendZuulResponse(true);// 对该请求进行路由  
		context.setResponseStatusCode(200);  
		// 设值，让下一个Filter看到上一个Filter的状态  
		FilterKit.setFilterFlag(context,true);  
        return null;  
	}

	/**  
	 * <p>Title: checkToken</p>  
	 * <p>Description: 验证token的有效性</p>  
	 * @param token
	 * @return  
	 */ 
	private boolean checkToken(String token) {
		return true;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;// 前置过滤器  
	}

	@Override
	public int filterOrder() {
		return 6;// 优先级为0，数字越大，优先级越低 
	}

}
